package de.bk.timecalc.midlet.statemachine;

import java.util.Hashtable;

import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.Display;

public abstract class AbstractGuiState
{
  private final StateMachine stateMachine;
  private final Hashtable transitions;

  AbstractGuiState(StateMachine stateMachine)
  {
    this.stateMachine = stateMachine;
    this.transitions = new Hashtable();
  }

  void addTransition(Command command, AbstractGuiState target)
  {
    this.transitions.put(command, target);
  }

  boolean followTransition(Command command)
  {
    AbstractGuiState newState = this.getTransition(command);
    if (newState == null)
    {
      return false;
    }
    else
    {
      this.leave();
      newState.enter();
      return true;
    }
  }

  private AbstractGuiState getTransition(Command command)
  {
    return ((AbstractGuiState) this.transitions.get(command));
  }

  abstract void init();

  abstract void enter();

  void leave()
  {
    // empty default implementation
  }

  void destroy()
  {
    // empty default implementation
  }

  final StateMachine getStateMachine()
  {
    return this.stateMachine;
  }

  final Display getDisplay()
  {
    return Display.getDisplay(this.getStateMachine().getMidlet());
  }
}
